package com.scen.upload.shiro;

import com.scen.upload.domain.ActiverUser;
import com.scen.upload.domain.User;
import com.scen.upload.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * 自定义realm匹配用户名和密码
 */
public class UserRealm extends AuthorizingRealm {
    @Lazy
    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做认证【登录使用】
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户登录名
        String phone = token.getPrincipal().toString();
        //根据电话查询用户是否存在
        User user = this.userService.queryUserByPhone(phone);
        if (user != null) {
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            /**进行匹配密码
             * SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
             * userInfo, //用户名–此处传的是用户对象
             * userInfo.getPassword(), //密码—从数据库中获取的密码
             * salt,//盐
             * getName() //当前的realm名
             * );
             */
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return info;
        } else {
            //代表用户不存在
            return null;
        }
    }

    /**
     * 做授权【登陆成功之后判断用户是否有某个菜单或按钮的权限】
     *
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        ActiverUser activerUser = (ActiverUser) principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

}
